package ogdkp.om;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LootCache {

	private static LootCache INSTANCE;

	public static LootCache getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new LootCache();
		}
		return INSTANCE;
	}

	private static final List<LootItem> loot = new ArrayList<LootItem>();

	private LootCache() {
		loadCache();
	}

	private void loadCache() {
		final File file = new File("loot/loot.db");
		try {
			final FileReader freader = new FileReader(file);
			final BufferedReader reader = new BufferedReader(freader);
			String item;
			while ((item = reader.readLine()) != null) {
				final String[] array = item.split("\\|");
				if (array.length > 3) {
					loot.add(new LootItem(array[0], array[1], array[2], Integer.parseInt(array[3])));
				}
			}
			reader.close();
			freader.close();
		} catch (final IOException e) {
			e.printStackTrace();
		}
		Collections.sort(loot, new Comparator<LootItem>() {

			@Override
			public int compare(final LootItem o1, final LootItem o2) {
				return o1.getName().compareTo(o2.getName());
			}

		});

	}

	public List<LootItem> getLootItems() {
		return loot;
	}

	public String[] getLocations() {
		final List<String> locations = new ArrayList<String>();
		for (final LootItem item : loot) {
			final String loc = item.getRaid();
			if (!locations.contains(loc)) {
				locations.add(loc);
			}
		}
		return locations.toArray(new String[locations.size()]);
	}

	public String[] getLootNamesFor(final String boss) {
		final List<String> names = new ArrayList<String>();
		for (final LootItem item : loot) {
			if (boss == null) {
				names.add(item.getName());
			} else {
				if (boss.equals(item.getBoss())) {
					names.add(item.getName());
				}
			}
		}
		return names.toArray(new String[names.size()]);
	}

	public String[] getBosses(final String raid) {
		final List<String> bosses = new ArrayList<String>();
		for (final LootItem item : loot) {
			if (bosses.contains(item.getBoss()) == false && (raid == null || item.getRaid().equals(raid))) {
				bosses.add(item.getBoss());
			}
		}
		Collections.sort(bosses);
		return bosses.toArray(new String[bosses.size()]);
	}

	public LootItem getLootItemFor(final String name) {
		if (name != null) {
			for (final LootItem item : loot) {
				if (name.equals(item.getName())) {
					return item;
				}
			}
		}
		return null;
	}
}
